﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CommonLib
{

    public class Crc16Util
    {

        /**CRC值*/
        private int _value = 0x8005;

        private  int[] _crc16Table = new int[256];

        public  Crc16Util()
        { // 初始化CRC16 码表
            int cRc16 = 0x0000;
            short i, j, k;
            for (i = 0, k = 0; i < 256; i++, k++)
            {
                cRc16 = i << 8;
                for (j = 8; j > 0; j--)
                {
                    if ((cRc16 & 0x8000) != 0)
                    {
                        cRc16 = (cRc16 <<= 1) ^ _value;
                    }
                    else
                    {
                        cRc16 <<= 1;
                    }
                }
                _crc16Table[k] = cRc16;
            }
        }

        /**
 * 计算CRC16值
 *
 * @param data
 * @return
 */
        public short CalcCrc16(byte[] data)
        {
            return CalcCrc16(data, 0, data.Length);
        }

        /**
 * 计算CRC16值
 *
 * @param data
 * @param startIndex 开始索引
 * @param nLength 长度
 * @return
 */
        public short CalcCrc16(byte[] data, int startIndex, int nLength)
        {
            int cRc16 = _crc16Table[255];
            int index = startIndex;
            while (nLength > 0)
            {
                cRc16 = (cRc16 << 8) ^ _crc16Table[((cRc16 >> 8) ^ data[index]) & 0xff];
                nLength--;
                index++;
            }
            return (short)cRc16;
        }

   

    }
}
